<template>
  <div class="carnbon-container">
    <el-breadcrumb separator="/" style="padding:0px 20px 10px">
      <el-breadcrumb-item>能碳管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="'/carbonMgr/tradingBook'">交易账簿</el-breadcrumb-item>
    </el-breadcrumb>

		<div class="search-form">
			<el-form inline :model="searchFromData">
				<el-form-item label="主体" prop="name">
					<el-select v-model="searchFromData.name" placeholder="请选择主体" style="width:180px;">
						<el-option v-for="(op, oIndex) in ['周口市中医院']"  :key="op" :label="op" :value="op" />
					</el-select>
				</el-form-item>
				<el-form-item label="时间范围" prop="tradeTimeRange">
					<el-date-picker style="width:250px;" v-model="searchFromData.tradeTimeRange" type="daterange" range-separator="-" start-placeholder="起始日期" end-placeholder="结束日期"> </el-date-picker>
				</el-form-item>
				<el-form-item label="交易品种" prop="realPoint">
					<el-select v-model="searchFromData.realPoint" placeholder="请选择交易品种" style="width:180px;">
						<el-option v-for="item in tradeClassOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="交易类型" prop="tradeType">
					<el-select v-model="searchFromData.tradeType" placeholder="请选择交易类型" style="width:180px;">
						<el-option v-for="item in tradeTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
					</el-select>
				</el-form-item>
				<el-form-item label="交易对手" prop="tradeTo">
					<el-input v-model.trim="searchFromData.tradeTo" placeholder="请输入交易对手" style="width:120px" />
				</el-form-item>
				<el-button @click="onReset">清除</el-button>
				<el-button class="saveBtn" type="primary" @click="onSearchClicked">查询</el-button>
			</el-form>
		</div>

    <div class="list">
      <CustomTableTrading
              id="authList"
              class="auth-list"
              :table-config="tableConfig"
              :is-show-pagination="false"
              :search-callback="searchCallback"
              :is-refresh="isRefresh"
              :isShowSelect="false"
      >
      </CustomTableTrading>
    </div>

    <addForm ref="addFormRef" @done="handleOk" />
    <editForm ref="editFormRef" @done="handleOk" />
  </div>
</template>
<script setup lang="ts">
  import { appAuthList, appBacthPass, appDeny, appPass } from '@/ajax/index';
  import { DateFormat } from '../../../utils/storage';
  import { pointOptions, tradeClassOptions, projectOptionsMock, tableDataMock, ProjectOption, TableDataProps, TradeOption, tradeType1Options, tradeType2Options } from './data';
  import CustomTableTrading from '@/components/CustomTableTrading.vue';
  import addForm from './addForm.vue'
  import editForm from './editForm.vue'
  import { dateFormat, FormatsEnums } from '@/utils/dateUtil';
  import { getCurrentInstance, ref,computed, reactive } from 'vue';
  import { useRouter } from 'vue-router';
  const { ctx , proxy } = getCurrentInstance() as any;

  let router = useRouter()

  const searchFromData = reactive({
    name:'',
    projectId:'',
    tradeTimeRange:'',
    realPoint: null,
    tradeType:null,
    tradeTo: ''

  })

  const tableConfig = ref({})
  const isRefresh = ref(false)
  
  const addFormRef = ref(null)
  const openAddForm = () => {
    addFormRef.value && addFormRef.value.open();
  }

  const editFormRef = ref(null)
  const openEditForm = (row) => {
    editFormRef.value && editFormRef.value.open(row);
  }

    const tradeTypeOptions = computed(() => {
  if(searchFromData.realPoint===1){
    return tradeType1Options
  }if(searchFromData.realPoint===2){
    return tradeType2Options
  }
  return []
})

  const calcuTradeClassName = (tclass) => {
    const find = tradeClassOptions.find(item => item.id === tclass)
    if(find){
      return find.name
    }
    return ''
  }

  const calcuTradeTypeName = (tclass,tType) => {
    let findOptions = []

    if(tclass === 1){
      findOptions = tradeType1Options
    }else if(tclass === 2){
      findOptions = tradeType2Options
    }
    const find = findOptions.find(item => item.id === tType)
    if(find){
      return find.name
    }
    return ''
  }

   const calcuNumber = (num) => {
    if(num){
      return num
    }
    return 'N/A'
  }
  
  //type：0-全部授权 1-授权通过
  const submit = (type: number, data: any) => {
    const msgLabel = {
      0: "全部授权通过",
      1: "通过"
    }
    ElMessageBox.confirm(
      `确定要${msgLabel[type]}吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(async () => {
      let res = {
        succ: false
      }
      if (type == 0) {
        res = await appBacthPass({})
      }
      if (type == 1) {
        res = await appPass({id: data.id})
      }
      if (res.succ) {
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        isRefresh.value = true
        nextTick(()=>{
          isRefresh.value = false
        })
      }
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '您已取消操作',
      })
    })
  }

  const handleOk = () => {
    console.log('列表需要刷新');
  }

  const onReset = (row: any) => {
  }

  const go = (path: string) => {
    router.push({ name:path})
  }

  const statusMap = {
    approved: "已通过",
    declined: "已驳回",
    // requesting: "请求中",
  }
  tableConfig.value = {
    // 表格顶部的操作按钮
    'actionBtns': [
      {
        'type': `primary`, // 按钮类型
        'icon': `Plus`, // 按钮上的图标
        label: `新增`, // 按钮展示的文字
        'isRefresh': false, // 执行完事件是否刷新页面
        'btnCallback': openAddForm // 事件回调
      },
    ],
    // 是否隐藏序号列
    'isHiddenIndex': {
      'type': false,
      'required': false,
      'default': false
    },
    'isRefresh': false,
    // 表格展示配置
    'tableHeader': [
      {
        label: '主体',
        innerHTML: (row: any) => {
          return `${row.tradeFrom.name}`
        }
      },
      {
        label: '时间范围',
        prop: 'tradeAt',
      },
      {
        label: '交易品种',
        prop: 'name',
        innerHTML: (row: any) => {
          return `${calcuTradeClassName(row.tradeClass)}`
        }
      },
      {
        label: '交易类型',
        prop: 'name',
        innerHTML: (row: any) => {
          return `${calcuTradeTypeName(row.tradeClass,row.tradeType)}`
        }
      },
      {
        label: '数量(t)',
        prop: 'amount',
      },
      {
        label: '价格(元/t)',
        prop: 'unitPrice',
         innerHTML: (row: any) => {
          return `${calcuNumber(row.traunitPricedeClass)}`
        }
      },
      {
        label: '交易对手',
        prop: 'tradeTo',
      }, {
        label: '总金额(元)',
        prop: 'totalPrice',
         innerHTML: (row: any) => {
          return `${calcuNumber(row.totalPrice)}`
        }
      },
      {
        label: '操作',
        prop: 'id',
        fixed:  'right',
        btns: [
          {
            label: '编辑',
            btnCallback: (row) => {
              openEditForm(row)
            }
          },
          {
            label: '删除',
            btnCallback: () => {
              ElMessageBox.confirm(
                `确定要删除吗？`,
                '提示',
                {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                }
              ).then(async () => {
                let res = {
                  succ: false
                }
                if (type == 0) {
                  res = await appBacthPass({})
                }
                if (type == 1) {
                  res = await appPass({id: data.id})
                }
                if (res.succ) {
                  ElMessage({
                    type: 'success',
                    message: '操作成功',
                  })
                  isRefresh.value = true
                  nextTick(()=>{
                    isRefresh.value = false
                  })
                }
              }).catch(() => {
                ElMessage({
                  type: 'info',
                  message: '您已取消操作',
                })
              })
            }
          }
        ],
        width:'300px'
      },
    ],

  }

  const searchCallback = async () => {
    const params = {
      pageNumber:1,
      pageSize:1000
    }
    try {
      const res = await appAuthList(params)
      let list = res.content.data.requests || []
      console.log('list',list);
      if (!res.succ) {
        return
      }
      list = tableDataMock

      return {
        "success": true,
        "message": "string",
        "content": {
          "size": 10,
          "records": list,
          "current": 0,
          "pages": 1,
          "total": 7
        }
      }
    } catch (error) {
      console.log("error", error)
    }

    // return {
    //     "success": true,
    //     "message": "string",
    //     "content": {
    //         "size": 0,
    //         "records": tableData,
    //         "current": 0,
    //         "pages": 0,
    //         "total": 0
    //     },
    //     "options": {
    //         "additionalProp1": {},
    //         "additionalProp2": {},
    //         "additionalProp3": {}
    //     }
    // }
  }

  const created = () => {

  }

</script>
<style lang="scss" scoped>
  .space-auth-container {

  }
</style>
<style lang="scss">
  .space-auth-status-tip {
    max-width: 300px;
  }
  .space-auth-container {
    .auth-list {
      .top {
        padding: 0;
      }
      .tableCon {
        line-height: 20px;
        padding: 15px 0 0 0;
        th {
          background-color: #F3F4F6 !important;
          color: #94979E !important;
        }
      }
      .el-table th.el-table__cell>.cell{
        font-size: 12px !important;
        font-weight: 500;
        color: #94979E;
      }
      .el-table td.el-table__cell>.cell{
        font-size: 13px;
        font-weight: 400;
        color: #343333;
      }
      .el-button.el-button--text {
        font-size: 13px;
        font-weight: 400;
        color: #088D9E;
      }
    }
  }
</style>